/**
 * Created by sicongdu on 17-11-3.
 */
var md5 = require("../../../md5").md5

const express = require('express');
var hackson = express.Router();

var fs = require('fs');
var path = require("path");
var formidable = require('formidable');

hackson.use(express.static(path.resolve(__dirname, './images')));


var err = {
  error_no: 2,
  error_msg: "内部错误，请联系杜思聪～"
}

//get list of marathons
hackson.post("/marathons", function (req, res, next) {
  var marathons = require("./hackson_model").marathons
  marathons.find({}, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        marathons: documents
      })
    }
  })
});

//create a marathon
hackson.post("/new_marathon", function (req, res, next) {
  var marathons = require("./hackson_model").marathons
  marathons.create({
    name: req.body.name,
    start_time: req.body.start_time,
    stop_time: req.body.stop_time,
    address: req.body.address,
    organizer: req.body.organizer,
    participants: req.body.participants,
    detail: req.body.detail,
    votes_for_teacher: req.body.votes_for_teacher,
    weight_for_teacher: req.body.weight_for_teacher,
    votes_for_student: req.body.votes_for_student,
    dimensions_for_vote: req.body.dimensions_for_vote,
    students: "",
    status: "0"
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        marathons: doc
      })
    }
  })
});

//get_groups_by_marathon_id
hackson.post("/get_groups_by_marathon_id", function (req, res, next) {
  var groups = require("./hackson_model").groups
  var status = req.body.status
  var level = []

  if (status == "0" || status == "1" || status == "2" || status == "3") {
    level.push("1")
    level.push("")
    level.push(undefined)
    level.push(null)
  } else if (status == "4" || status == "5") {
    level.push("2")
  } else if (status == "6") {
    level.push("1")
    level.push("")
    level.push(undefined)
    level.push(null)
    level.push("2")
  }

  groups.find({
      marathon_id: req.body.marathon_id,
      level: {
        $in: level
      }
    }, null, {sort: {'_id': 1}},
    (error, documents) => {
      if (error) {
        res.send(err)
      } else {
        res.send({
          error_no: 0,
          error_msg: "ok",
          marathons: documents
        })
      }
    })
});

//get details of a group
hackson.post("/get_details_by_marathon_id_and_group_name", function (req, res, next) {
  var groups = require("./hackson_model").groups
  var students = require("../mongo_student").students
  groups.findOne({
    marathon_id: req.body.marathon_id,
    name: req.body.name,
  }, (error, document) => {
    if (error) {
      res.send(err)
    } else {
      students.find({
        studentNo: {$in: JSON.parse(JSON.stringify(document)).members.split(",")}
      }, (error, stts) => {
        if (error) {
          res.send(err)
        } else {
          var members = []
          var captain = ""
          var mem_num = JSON.parse(JSON.stringify(document)).members.split(",")

          for (var i = 0; i < mem_num.length; i++) {
            for (var j = 0; j < stts.length; j++) {
              if (mem_num[i] == stts[j].studentNo && mem_num[i] == JSON.parse(JSON.stringify(document)).captain) {
                captain = stts[j].name
              } else if (mem_num[i] == stts[j].studentNo && mem_num[i] != JSON.parse(JSON.stringify(document)).captain) {
                members.push(stts[j].name)
              }
            }
          }
          res.send({
            error_no: 0,
            error_msg: "ok",
            group: {
              members: members,
              captain: captain,
              document: document,
              // stts: stts,
              detail: document.detail,
              url: document.url,
              photo: document.photo
            }
          })
        }

      })

    }
  })
});

//give a vote
hackson.post("/vote", function (req, res, next) {
  var votes = require("./hackson_model").votes
  votes.create({
    role: req.body.role, // 1 student,  2 teacher, 3 admin, 4 donator
    id: req.body.id,
    marathon_id: req.body.marathon_id, //id1
    vote: req.body.vote, //id2
    level: req.body.level
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        marathons: doc
      })
    }
  })
});

//check the person whether has given a vote
hackson.post("/check_voted", function (req, res, next) {
  var votes = require("./hackson_model").votes
  var status = req.body.status
  var level = "0"
  if (status == "4" ) {
    level = "2"
  } else if (status == "2"){
    level = "1"
  }

  votes.find({
    role: req.body.role, // 1 student,  2 teacher, 3 admin, 4 donator
    id: req.body.id,
    marathon_id: req.body.marathon_id, //id1
    level: level
  }, (error, docs) => {
    if (error) {
      res.send(err)
    } else if (docs.length == 1) {
      res.send({
        error_no: 1,
        error_msg: "已经投过票了"
      })
    } else if (docs.length == 0) {
      res.send({
        error_no: 0,
        error_msg: "ok"
      })
    }
  })
});

//check the student whether has signed up for marathon
hackson.post("/check_signed_for_student", function (req, res, next) {
  var marathon = require("./hackson_model").marathons
  marathon.findOne({
    name: req.body.marathon_id
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      var students = JSON.parse(JSON.stringify(doc)).students
      if (students.split(",").includes(req.body.studentNo)) {
        res.send({
          error_no: 0,
          error_msg: "ok"
        })
      } else {
        res.send({
          error_no: 1,
          error_msg: "您没有参加此次活动"
        })
      }

    }
  })
});

//give a trace point
hackson.post("/trace", function (req, res, next) {
  var traces = require("./hackson_model").traces
  traces.create({
    role: req.body.role, // 1 student,  2 teacher, 3 admin, 4 donator
    id: req.body.id,
    marathon_id: req.body.marathon_id, //id1
    name: req.body.name, //id2
    time: req.body.time
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        marathons: doc
      })
    }
  })
});

//sign up as a group
hackson.post("/sign_up", function (req, res, next) {
  var groups = require("./hackson_model").groups
  var marathon = require("./hackson_model").marathons

  marathon.findOne({
    name: req.body.marathon_id, //id1
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      var students_temp = req.body.members
      if (doc.students) {
        students_temp = JSON.parse(JSON.stringify(doc)).students
        var present_students_array = students_temp.split(",")
        var new_students_array = req.body.members.split(",")

        for (var i = 0; i < new_students_array.length; i++) {
          if (!present_students_array.includes(new_students_array[i])) {
            students_temp += "," + new_students_array[i]
          }
        }
      }

      marathon.update({
        name: req.body.marathon_id, //id1
      }, {
        $set: {students: students_temp}
      }, (error) => {
        if (error) {
          res.send(err)
        } else {

          groups.create({
            marathon_id: req.body.marathon_id, //id1
            name: req.body.name, //id2
            members: req.body.members,
            captain: req.body.captain,
            detail: req.body.detail,
            url: "",
            photo: "",
            level: "1"
          }, (error, doc) => {
            if (error) {
              res.send(err)
            } else {
              res.send({
                error_no: 0,
                error_msg: "ok",
                marathons: doc
              })
            }
          })

        }
      })
    }
  })

});

//improve the text information of projects
hackson.post("/improve", function (req, res, next) {
  var groups = require("./hackson_model").groups
  groups.update({
    marathon_id: req.body.marathon, //id1
    name: req.body.group, //id2
  }, {
    $set: {
      name: req.body.name, //id2
      members: req.body.members,
      captain: req.body.captain,
      detail: req.body.detail,
      url: req.body.url,
    }
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        group: doc
      })
    }
  })
});

//upload pictures
hackson.post("/upload_pictures", function (req, res, next) {

  var form = new formidable.IncomingForm();
  // //设置编辑
  // form.encoding = 'utf-8';
  //设置文件存储路径
  form.uploadDir = __dirname + "/images";
  //保留后缀
  form.keepExtensions = true;
  // //设置单文件大小限制
  // form.maxFieldsSize = 2 * 1024 * 1024;
  //form.maxFields = 1000;  设置所以文件的大小总和

  form.parse(req, function (err, fields, files) {
    // res.send({
    //   fields: fields,
    //   files: files
    // });
    // res.end()
    //console.log(fields);
    // console.log(files.image.path);
    // console.log('文件名:'+files.image.name);
    // var t = (new Date()).getTime();
    // //生成随机数
    // var ran = parseInt(Math.random() * 8999 +10000);

    //拿到扩展名
    var extname = path.extname(files.image.name);

    //path.normalize('./path//upload/data/../file/./123.jpg'); 规范格式文件名
    // var oldpath = path.normalize(files.image.path);
    var oldpath = files.image.path

    //新的路径
    let newfilename = md5(fields.marathon) + "_" + md5(fields.group) + extname;
    var newpath = __dirname + "/images/" + newfilename;
    // console.log('oldpath:'+oldpath+' newpath:'+newpath);

    fs.exists(newpath, (result) => {
      if (result) {
        fs.unlink(newpath, function (error) {
          if (error) {
            res.send({
              error_no: 2,
              error_msg: "内部错误，图片更新失败，请联系杜思聪～"
            })
          } else {
            fs.rename(oldpath, newpath, function (error) {
              if (error) {
                res.send({
                  error_no: 1,
                  error_msg: "改名失败" + error
                });
                res.end()
              } else {

                var groups = require("./hackson_model").groups
                groups.update({
                  marathon_id: fields.marathon, //id1
                  name: fields.group, //id2
                }, {
                  $set: {
                    photo: "https://www.ourspark.org/hackson/" + newfilename
                  }
                }, (error, doc) => {
                  if (error) {
                    res.send(err)
                    res.end()
                  } else {
                    res.send({
                      error_no: 0,
                      error_msg: "ok",
                      group: doc
                    })
                    res.end()
                  }
                })

              }
            });
          }
        })
      } else {
        fs.rename(oldpath, newpath, function (error) {
          if (error) {
            res.send({
              error_no: 1,
              error_msg: "改名失败" + error
            });
            res.end()
          } else {

            var groups = require("./hackson_model").groups
            groups.update({
              marathon_id: fields.marathon, //id1
              name: fields.group, //id2
            }, {
              $set: {
                photo: "https://www.ourspark.org/hackson/" + newfilename
              }
            }, (error, doc) => {
              if (error) {
                res.send(err)
                res.end()
              } else {
                res.send({
                  error_no: 0,
                  error_msg: "ok",
                  group: doc
                })
                res.end()
              }
            })

          }
        });
      }

    })
    //res.end(util.inspect({fields: fields, files: files}));
  });
});

//check id for group
hackson.post("/check_id_for_group", function (req, res, next) {
  var groups = require("./hackson_model").groups
  groups.findOne({
    marathon_id: req.body.marathon_id, //id1
    name: req.body.name, //id2
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else if (doc != null) {
      res.send({
        error_no: 2,
        error_msg: "项目名称已被注册"
      })
    } else if (doc == null) {
      res.send({
        error_no: 0,
        error_msg: "ok"
      })
    }
  })
});

//check studentNo when group sign up
hackson.post("/check_studentNo_when_group_sign_up", function (req, res, next) {
  var configs = require("../mongo_non_student").configs

  var students = req.body.students
  var length = students.split(",").length

  configs.find({
    type: "1",
    key: {$in: students.split(",")}
  }, (error, documents) => {
    if (error) {
      res.send(err)
    }
    else if (documents.length == 0) {
      res.send({
        error_no: 2,
        error_msg: "所有学号未注册"
      })
    } else if (documents.length != length) {
      res.send({
        error_no: 2,
        error_msg: "部分学号未注册",
        documents: documents
      })
    } else if (documents.length == length) {
      res.send({
        error_no: 0,
        error_msg: "ok"
      })
    }
  })
});

//check id for marathon
hackson.post("/check_id_for_marathon", function (req, res, next) {
  var marathons = require("./hackson_model").marathons
  marathons.findOne({
    name: req.body.name
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else if (doc != null) {
      res.send({
        error_no: 1,
        error_msg: "already exists"
      })
    } else if (doc == null) {
      res.send({
        error_no: 0,
        error_msg: "ok"
      })
    }
  })
});

//set marathon status
hackson.post("/set_marathon_status", function (req, res, next) {
  var marathons = require("./hackson_model").marathons

  var flag = req.body.flag
  var status = parseInt(req.body.status)

  if (flag == "1") {
    if (status == 6) {
      res.send({
        error_no: 1,
        error_msg: "马拉松已结束"
      })
    } else {
      marathons.update({
        name: req.body.name
      }, {$set: {status: status + 1}}, (error, doc) => {
        if (error) {
          res.send(err)
        } else {
          res.send({
            error_no: 0,
            error_msg: "状态前进成功"
          })
        }
      })
    }
  } else if (flag == "2") {
    if (status == 0) {
      res.send({
        error_no: 1,
        error_msg: "马拉松未开始"
      })
    } else {
      marathons.update({
        name: req.body.name
      }, {$set: {status: status - 1}}, (error, doc) => {
        if (error) {
          res.send(err)
        } else {
          res.send({
            error_no: 0,
            error_msg: "状态后退成功"
          })
        }
      })

    }
  }
});

//get voting results of a marathon
hackson.post("/result", function (req, res, next) {
  var votes = require("./hackson_model").votes

  var status = req.body.status

  var level = []
  if(status != "6"){
    if (status == "0" || status == "1" || status == "2" || status == "3") {
      level.push("1")
      level.push("")
      level.push(undefined)
      level.push(null)
    }
    else if (status == "4" || status == "5") {
      level.push("2")
    }

    votes.find({
      marathon_id: req.body.marathon_id,
      level: {
        $in: level
      }
    }, (error, documents) => {
      if (error) {
        res.send(err)
      }
      else {
        var results = {}
        var votes_temp = documents.slice(0)

        var votes = votes_temp.map((person_vote) => {
          return JSON.parse(person_vote.vote)
        })

        for (var j in votes[0]) {
          results[j] = {}
        }
        results["总票数"] = {}

        for (var i in votes) {
          for (var j in votes[i]) {
            for (var k in votes[i][j]) {
              if (results[j].hasOwnProperty(votes[i][j][k])) {
                results[j][votes[i][j][k]] += 1
              } else {
                results[j][votes[i][j][k]] = 1
              }

              if (results["总票数"].hasOwnProperty(votes[i][j][k])) {
                results["总票数"][votes[i][j][k]] += 1
              } else {
                results["总票数"][votes[i][j][k]] = 1
              }

            }
          }
        }

        res.send({
          error_no: 0,
          error_msg: "ok",
          results: [results]
        })
      }
    })
  }
  else if (status == "6") {
    level.push("2")
    var results_one = {}
    var results_two = {}

    votes.find({
      marathon_id: req.body.marathon_id,
      level: {
        $in: ["1", "", undefined, null]
      }
    }, (error, documents) => {
      if (error) {
        res.send(err)
      } else {
        var results = {}
        var votes_temp = documents.slice(0)

        var votes1 = votes_temp.map((person_vote) => {
          return JSON.parse(person_vote.vote)
        })

        for (var j in votes1[0]) {
          results[j] = {}
        }
        results["总票数"] = {}

        for (var i in votes1) {
          for (var j in votes1[i]) {
            for (var k in votes1[i][j]) {
              if (results[j].hasOwnProperty(votes1[i][j][k])) {
                results[j][votes1[i][j][k]] += 1
              } else {
                results[j][votes1[i][j][k]] = 1
              }

              if (results["总票数"].hasOwnProperty(votes1[i][j][k])) {
                results["总票数"][votes1[i][j][k]] += 1
              } else {
                results["总票数"][votes1[i][j][k]] = 1
              }

            }
          }
        }

        results_one = results

        votes.find({
          marathon_id: req.body.marathon_id,
          level: {
            $in: ["2"]
          }
        }, (error, documents) => {
          if (error) {
            res.send(err)
          } else {
            var results = {}
            var votes_temp = documents.slice(0)

            var votes = votes_temp.map((person_vote) => {
              return JSON.parse(person_vote.vote)
            })

            for (var j in votes[0]) {
              results[j] = {}
            }
            results["总票数"] = {}

            for (var i in votes) {
              for (var j in votes[i]) {
                for (var k in votes[i][j]) {
                  if (results[j].hasOwnProperty(votes[i][j][k])) {
                    results[j][votes[i][j][k]] += 1
                  } else {
                    results[j][votes[i][j][k]] = 1
                  }

                  if (results["总票数"].hasOwnProperty(votes[i][j][k])) {
                    results["总票数"][votes[i][j][k]] += 1
                  } else {
                    results["总票数"][votes[i][j][k]] = 1
                  }

                }
              }
            }

            results_two = results

            res.send({
              error_no: 0,
              error_msg: "ok",
              results: [results_one, results_two]
            })
          }
        })
      }
    })
  }


});


var students = require("../mongo_student").students
var map = {}
var map_group_school = (req, res, group_list, i) => {

  students.findOne({
    studentNo: group_list[i].captain
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      map[group_list[i].name] = doc.school

      // console.log("判断：" +  i  + "==" +  group_list.length + " ：" + (i == group_list.length))
      if (i == group_list.length - 1) {
        res.send({
          error_no: 0,
          error_msg: "ok",
          map: map
        })
      } else {
        map_group_school(req, res, group_list, i + 1)
      }

    }

  })
}
//get mapping between group and school
hackson.post("/map_group_school", function (req, res, next) {
  var groups = require("./hackson_model").groups

  groups.find({
    marathon_id: req.body.marathon_id
  }, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      var group_list = JSON.parse(JSON.stringify(documents))

      map_group_school(req, res, group_list, 0)

    }

  })
});

//get user information
hackson.post("/getUserInfo", function (req, res, next) {
  var non_students = require("../mongo_non_student")
  var students = require("../mongo_student").students
  var getOpenId = require("../login/getOpenId").getOpenId

  getOpenId(req.body.code,

    (openid, res, doc) => {
      non_students.configs.findOne({
        openId: openid
      }, (error, doc) => {
        if (error) {
          res.send(err)
        } else if (doc != null) {
          var kind = doc.type
          var id = doc.key

          if (kind == "1") {
            students.findOne({studentNo: id}, (error, doc) => {
              if (error) {
                res.send(err)
              } else if (doc == null) {
                res.send({
                  error_no: 1,
                  error_msg: "查无此人(不应该呀)"
                })
              } else if (doc != null) {
                res.send({
                  error_no: 0,
                  error_msg: "ok",
                  user: doc,
                  type: "1"
                })
              }
            })
          } else if (kind == "2") {
            non_students.teachers.findOne({teacherNo: id}, (error, doc) => {
              if (error) {
                res.send(err)
              } else if (doc == null) {
                res.send({
                  error_no: 1,
                  error_msg: "查无此人(不应该呀)"
                })
              } else if (doc != null) {
                res.send({
                  error_no: 0,
                  error_msg: "ok",
                  user: doc,
                  type: "2"
                })
              }
            })
          } else if (kind == "3") {
            non_students.admins.findOne({adminNo: id}, (error, doc) => {
              if (error) {
                res.send(err)
              } else if (doc == null) {
                res.send({
                  error_no: 1,
                  error_msg: "查无此人(不应该呀)"
                })
              } else if (doc != null) {
                res.send({
                  error_no: 0,
                  error_msg: "ok",
                  user: doc,
                  type: "3"
                })
              }
            })
          } else if (kind == "4") {
            non_students.donators.findOne({donatorNo: id}, (error, doc) => {
              if (error) {
                res.send(err)
              } else if (doc == null) {
                res.send({
                  error_no: 1,
                  error_msg: "查无此人(不应该呀)"
                })
              } else if (doc != null) {
                res.send({
                  error_no: 0,
                  error_msg: "ok",
                  user: doc,
                  type: "4"
                })
              }
            })
          }


        } else if (doc == null) {
          res.send({
            error_no: 1,
            error_msg: "查无此人(登录有问题)"
          })
        }
      })
    },

    res)

});

// promote
hackson.post("/promote", function (req, res, next) {
  var groups = require("./hackson_model").groups

  groups.update({
    marathon_id: req.body.marathon_id,
    name: {$in: req.body.promote.split(",")}
  }, {
    $set: {
      level: "2"
    }
  }, {multi: true}, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        documents: documents
      })
    }
  })
});


// var sign_up_save = require('./student').save;
// var mark = require('./mark').mark;
// var mark_save = require('./mark_save').mark;
// var login = require('./login').login;
//
// var vote = 0
//
// hackson.get("/index", function(req, res, next){
//     res.render('login', {layout: null});
// });
//
// hackson.post("/login", function(req, res, next){
//     login(req,res)
// });
//
// hackson.get("/sign_up", function(req, res, next){
//     res.render('sign_up', {layout: null});
// });
//
// hackson.post("/sign_up_save", function(req, res, next){
//     sign_up_save(req,res)
// });
//
// hackson.post("/group_sign", function(req, res, next){
//     // if(vote == 0){
//     //     res.render('group_sign', {layout: null});
//     // }else {
//     //     mark(req, res)
//     // }
//
// });
//
// hackson.get("/mark", function(req, res, next){
//    // save(req, res)
// });
//
// hackson.post("/mark_save", function(req, res, next){
//    // mark_save(req, res)
// });

module.exports = hackson;
